package com.zuoyy.admin.system.controller;

import cn.hutool.core.io.resource.UrlResource;
import com.zuoyy.admin.common.BaseController;
import com.zuoyy.admin.common.component.actionLog.action.StatusAction;
import com.zuoyy.admin.common.component.actionLog.annotation.ActionLog;
import com.zuoyy.admin.common.component.actionLog.annotation.EntityParam;
import com.zuoyy.admin.system.service.FileInterface;
import com.zuoyy.common.enums.StatusEnum;
import com.zuoyy.common.utils.DateUtil;
import com.zuoyy.common.utils.HttpServletUtil;
import com.zuoyy.common.utils.StatusUtil;
import com.zuoyy.common.vo.JsonResponse;
import com.zuoyy.modules.common.utils.DownLoadUtil;
import com.zuoyy.modules.system.domain.SysFile;
import com.zuoyy.modules.system.query.FileQuery;
import com.zuoyy.modules.system.service.FileService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 
 */
@Controller
@RequestMapping("/system/file")
public class FileController extends BaseController {

    //页面地址
    private static final String PAGE_PATH = "/system/file";
    //权限标示
    private static final String PERMISSION_FLAG = "system:file:";


    @Autowired
    private FileInterface fileInterface;
    @Autowired
    private DownLoadUtil downLoadUtil;
    @Autowired
    private FileService fileService;
    @Value("${project.upload.path}")
    private String rootPath;


    @GetMapping("/index.shtml")
    @RequiresPermissions(PERMISSION_FLAG+"index")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("res", getMyResources(request,response));
        return PAGE_PATH+"/index";
    }

    @GetMapping("/list/page")
    @RequiresPermissions(PERMISSION_FLAG+"list")
    public String listPage(Model model) {
        model.addAttribute("button", getPageButton(PERMISSION_FLAG+"list"));
        return PAGE_PATH+"/list";
    }

    @GetMapping("/add/page")
    @RequiresPermissions(PERMISSION_FLAG+"add")
    public String toAdd() {
        return PAGE_PATH+"/add";
    }

    @GetMapping("/edit/page/{id}")
    @RequiresPermissions(PERMISSION_FLAG+"edit")
    public String toEdit(@PathVariable("id") SysFile domain, Model model) {
        model.addAttribute("domain", domain);
        return PAGE_PATH+"/add";
    }



    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public JsonResponse getListPage(FileQuery query) {
        return fileInterface.getListPage(query);
    }

    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions({PERMISSION_FLAG+"add", PERMISSION_FLAG+"edit"})
    public JsonResponse save(@EntityParam @RequestBody SysFile domain) {
        return fileInterface.saveOrUpdate(domain);
    }

    @ResponseBody
    @RequestMapping("/status/{param}")
    @ActionLog(name = "状态", action = StatusAction.class)
    public JsonResponse status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<String> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        return fileInterface.updateStatus(statusEnum,ids);
    }


    // 存储文件
    @ResponseBody
    @RequestMapping(value = "/uploadFile",method={RequestMethod.POST})
    public JsonResponse uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String flx = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."),file.getOriginalFilename().length());
        String fileName = DateUtil.getTime()+flx;
        String path = rootPath+df.format(new Date())+ File.separator + fileName;
        File tempFile = new File(path);
        SysFile sysFile = new SysFile();
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                sysFile.setName(file.getOriginalFilename());
                sysFile.setPath(path);
                fileService.save(sysFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return JsonResponse.error("上传文件产生错误");
            } catch (IOException e) {
                e.printStackTrace();
                return JsonResponse.error("上传文件产生错误");
            }

        } else {
            return JsonResponse.error("上传文件为空");
        }
        return JsonResponse.success(sysFile);
    }


    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    public void downloadFile(@PathVariable("id") SysFile domain,HttpServletResponse response) throws Exception {
        downLoadUtil.downLoad(response,domain.getName(),domain.getPath());
    }


}